home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 8723 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.8 KB  |  64 lines

  1. Path: radmail.rad.co.il!usenet
  2. From: udi <udi@radnet.co.il>
  3. Newsgroups: comp.lang.c++
  4. Subject: Deleting Data Members that are Const Pointers / References?
  5. Date: 26 Feb 1996 07:50:31 GMT
  6. Organization: radnet.co.il
  7. Message-ID: <4groo7$4bt@radmail.rad.co.il>
  8. NNTP-Posting-Host: gate.radnet.co.il
  9. Mime-Version: 1.0
  10. Content-Type: text/plain; charset=us-ascii
  11. Content-Transfer-Encoding: 7bit
  12. X-Mailer: Mozilla 1.2N (Windows; I; 16bit)
  13.  
  14. news:comp.lang.c++#pvcybpuqx6p.fsf@hln56.pki-nbg.philips.de
  15.  
  16. Hi everybody,
  17.  
  18. I have a simple question regarding data members that are 
  19. constant pointers or references.
  20. Let's say I have a class Foo that has a data member xr (say of type int& 
  21. - in reality a different type) that is a constant reference. Objects of 
  22. class Foo must have an instance of xr during their lifetime, that's a 
  23. reason to have xr a reference. Also, xr must not change (not even 
  24. accidentaly, by some member function / friend of Foo), that's why I want 
  25. xr to be constant.Foo is always initialized with an int that was 
  26. allocated off the heap, but xr should cease to exist when Foo does, so 
  27. Foo is responsible to destroy xr and free the memory occupied by it.
  28. However, deleting a const reference (pointer) is not allowed (at least 
  29. according to Borland 4.5 and g++). This seems logical as the operand to
  30. delete is a void* and the compiler says he can't convert a const int* to
  31. a void*. 
  32. So, THE QUESTION IS:
  33. Is there an alternative to brutally casting the const away?
  34.  
  35. A sample code:
  36.  
  37. class Foo [
  38. public:
  39.    Foo(const int& xr1) : xr(xr1) {}
  40.    ~Foo() [ delete &xr; ] // ERROR - attempt to delete a constant pointer
  41. private:
  42.    int& xr;
  43. ];
  44.  
  45. int main() {
  46. int& xr1 = *(new int(100));
  47. Foo* fooP = new Foo(xr1);
  48. //...
  49. delete fooP;
  50. }
  51.  
  52. Alternative:
  53. ~Foo() [ delete (int*)(&xr); ] // BRUTAL CASTING
  54.  
  55. -- 
  56. Udi Ron
  57. RADNET
  58.  
  59. Tel: +972-3-6459585
  60. Fax: +972-3-6480582
  61. E-Mail: udi@gate.radnet.co.il
  62.  
  63.  
  64.